package com.acme.ioniolab.transportfile;

import java.io.IOException;

import com.acme.ioniolab.copyfile.FileCopier;
import com.acme.ioniolab.copyfile.implementation.IOFileCopier;
import com.acme.ioniolab.copyfile.implementation.NIOFileCopier;
import com.acme.ioniolab.transportfile.implementation.IOClient;
import com.acme.ioniolab.transportfile.implementation.IOServer;
import com.acme.ioniolab.transportfile.implementation.NIOClient;
import com.acme.ioniolab.transportfile.implementation.NIOServer;

public class TransportTest {

	private static final int NUM_ITERATIONS = 1000;

	public static void main(String[] args) throws IOException, InterruptedException {
		if (args.length < 3) {
			System.out.println("Usage: cl remotehost remoteport localFileToSend\n OR \n srv port fileToSave");
			return;
		}
		if ("srv".equals(args[0])) {
			System.out.println("Server running on port " + args[1]);
			server(new IOServer(), Integer.parseInt(args[1]), args[2]);
			Thread.sleep(500);
			server(new NIOServer(), Integer.parseInt(args[1]), args[2]);
		}
		if ("cl".equals(args[0])) {
			client(new IOClient(), args[1], Integer.parseInt(args[2]), args[3]);
			Thread.sleep(1000);
			client(new NIOClient(), args[1], Integer.parseInt(args[2]), args[3]);
		}
	}
	
	private static void server(Server fileServer, int port, String fileName) throws IOException {
		long time = fileServer.receiveFile(fileName, port);
		if (fileServer instanceof IOServer) {
			System.out.printf("File transfered with IO in %d ms\n", time);
		}
		else {
			System.out.printf("File transfered with NIO in %d ms\n", time);
		}
	}
	
	private static void client(Client fileClient, String host, int port, String fileName) throws IOException {
		fileClient.transportFile(fileName, host, port);
	}
}
